package kr.saeildamil.androidforstudy2.ch26;

import kr.saeildamil.androidforstudy2.R;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class EnglishWord extends Activity {
	WordDBHelper mHelper;
	EditText mText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch26_englishword);

		mHelper = new WordDBHelper(this);
		mText = (EditText) findViewById(R.id.edittext);
	}

	public void mOnClick(View v) {
		SQLiteDatabase db;
		ContentValues row;

		switch (v.getId()) {
		case R.id.insert:
			db = mHelper.getWritableDatabase();

			// dbHelper에서 지원하는 Method 사용;
			row = new ContentValues();
			row.put("eng", "boy");
			row.put("han", "남자아이");

			db.insert("dic", null, row);

			// SQL 문으로 삽입;
			String sql = "insert into dic values(null, 'girl' , '여자아이');";
			db.execSQL(sql);

			mHelper.close();
			
			mText.setText("Insert Successfully");
			break;

		case R.id.select:
			db = mHelper.getReadableDatabase();
			Cursor cursor;
			cursor = db.query("dic", new String[] { "_id", "eng", "han" },
					null, null, null, null, null);
			
			StringBuilder sb = new StringBuilder();
			
			sb = new StringBuilder();
			sb.append("컬럼 수 : " + cursor.getColumnCount() + "\n");
			sb.append("결과 레코드 수 : " + cursor.getCount() + "\n");
			
			while (cursor.moveToNext()) {
				sb.append(cursor.getInt(0) + " : ");
				sb.append(cursor.getString(1) + " = ");
				sb.append(cursor.getString(2) + "\n");
			}
			
			if (sb.length() == 0) {
				mText.setText("Set is Empty!");
			} else {
				mText.setText(sb.toString());
			}
			cursor.close();
			mHelper.close();
			break;
			
		case R.id.delete:
			db = mHelper.getWritableDatabase();
			db.delete("dic", null, null);
			// db.execSQL("Delete from dic");
			
			mText.setText("Delete Successfully");
			mHelper.close();
			break;

		case R.id.update:
			db = mHelper.getWritableDatabase();
			row = new ContentValues();
			row.put("han", "소년");
			db.update("dic", row, "eng='boy'", null);
		
			sql = "update dic set han='소녀' where eng='girl';";
			db.execSQL(sql);
			 
			mHelper.close();
			mText.setText("Update Successfully");
			break;
		}
	}

}
